import {Component} from "react";
import {State} from "./types.tsx";
import {Modal, Image, Button} from "antd";
import LazyIcon from "../../Icon";
import {fallbackImage} from '../../../../assets/settings.json'

class ImageDetail extends Component<any, State> {

    state: State = {
        visible: false,
        url: ''
    }

    download(url: string, fileName: string) {
        //图片的地址
        fetch(url)
            // 获取 blob 对象
            .then(res => res.blob())
            .then(blob => {
                const link = document.createElement('a');
                link.style.display = 'none';
                document.body.appendChild(link);
                const url = window.URL.createObjectURL(blob);
                link.href = url;
                link.download = fileName;
                link.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(link);
            })
    }

    showImageDetail = (variable: string) => {
        try {
            const {x6Img}: { x6Img: string } = JSON.parse(variable);
            const imgUrl = `${window.location.origin}/graph/${x6Img.substring(x6Img.lastIndexOf('/'))}`
            console.log(`graph url: ${imgUrl}`);
            this.setState({url: imgUrl}, () => this.setState({visible: true}))
        } catch (e) {
            throw `Preview failed: ${e}`;
        }
    }

    render() {
        const {visible, url} = this.state;
        return (
            <>
                <Modal title={"股权架构图预览"} open={visible} centered keyboard width={400} onCancel={() => this.setState({visible: false})}
                       footer={<><Button onClick={() =>this.download(url, 'graph.png')} type={"primary"} icon={<LazyIcon iconName={"Download"}/>}>下载</Button></>}>
                    <Image width={"100%"} height={"100%"} src={url} fallback={fallbackImage}></Image>
                </Modal>
            </>
        )
    }
}

export default ImageDetail
